<template>
  <div class="detail_video">
    <div class="video_header clearfix">
      <ul v-if="userInfo" class="header_left clearfix">
        <router-link :to="{name: 'index'}">
          <li class="return_btn"><img class="return_img" src="~/assets/image/return.svg" alt=""></li>
        </router-link>
        <li class="vider_title"> {{ courseInfo.courseName }}</li>
      </ul>
      <ul class="header_right clearfix">
        <li>
          <nuxt-link :to="{name: 'account-course'}" class="left_col">我的课程</nuxt-link>
        </li>
        <!--
        <li>
          <nuxt-link :to="{name: 'account'}" class="left_col">{{ userInfo.mobile }}</nuxt-link>
        </li>
        -->
      </ul>
    </div>
    <div class="video_body">
      <div class="video_content clearfix">
        <div class="win_box">
          <div
            id="player"
            ref="videobox"
            v-video-player:myVideoPlayer="playerOptions"
            class="confVideo vjs-custom-skin video-player"
            :playsinline="true"
            customEventName="customstatechangedeventname"
            @ready="playerReadied"
            @loadeddata="onPlayerLoadeddata($event)"
            @canplay="onPlayerCanplay($event)"
            @canplaythrough="onPlayerCanplaythrough($event)"
            @play="onPlayerPlay($event)"
            @playing="onPlayerPlaying($event)"
            @timeupdate="onPlayerTimeupdate($event)"
            @pause="onPlayerPause($event)"
            @waiting="onPlayerWaiting($event)"
            @ended="onPlayerEnded($event)"
            @statechanged="playerStateChanged($event)"
          />
          <span v-if="showTop" class="iconfont close_video" @click="stopVideo">&#xe616;</span>
        </div>
        <video-sidebar :course-info="courseInfo" :play-period="playPeriod" @playfunc="videoPlayByPeriodId" />
      </div>
    </div>
  </div>
</template>
<script>
import { playerOptions } from '@/pages/course/PlayerOptionss'
import { studyProgress } from '@/api/course'
import VideoSidebar from '@/components/course/VideoSidebar.vue'

export default {
  components: { VideoSidebar },
  props: {
    courseInfo: {
      type: Object,
      default: null
    },
    playPeriod: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      playerOptions: {},
      userStudy: {}, // 进度
      showTop: false,
      cateType: 0,
      tokenInfo: '',
      userInfo: ''
    }
  },
  mounted() {
    this.tokenInfo = this.$store.state.tokenInfo
    this.userInfo = this.$store.state.userInfo
  },
  methods: {
    // --------------------视频播放-开始-------------------- */
    // 初始化话播放-在onPlayerCanplay中调用
    initPlay(player) {
      console.log('initPlay>当前视频播放器实例对象', this.player)
      player.play()
    },

    /* 视频播放 */
    // 视频准备完毕
    playerReadied(player) {
      console.log('Readied>视频准备完毕!', player)
    },

    // 视频加载完成
    onPlayerLoadeddata(player) {
      console.log('Loadeddata>视频加载完成!', player)
    },

    // 可以播放视频
    onPlayerCanplay(player) {
      console.log('Canplay>可以播放视频!', player)
      // this.initPlay(player);
    },

    // 拖动视频条会触发事件-视频暂停>可以播放视频>可以播放视频至拖动位置>视频播放>视频加载中>可以播放视频>视频播放中>视频加载中>可以播放视频>视频播放中>视频加载中>可以播放视频>视频播放中>可以播放视频至拖动位置
    // 可以播放视频至拖动位置
    onPlayerCanplaythrough(player) {
      console.log('Canplaythrough>可以播放视频至拖动位置!', player)
    },

    // 视频播放
    onPlayerPlay(player) {
      console.log('Play>视频播放!', player)
    },

    // 视频暂停
    onPlayerPause(player) {
      console.log('Pause>视频暂停!', player)
    },

    // 视频播放中
    onPlayerPlaying(player) {
      console.log('Playing>视频播放中!', player)
    },

    // 视频播放结束
    onPlayerEnded(player) {
      console.log('Ended>视频播放结束!', player)

      const currentTime = player.cache_.currentTime // 当前播放时长
      const duration = player.cache_.duration // 视频总时长
      this.studyRecord(duration, currentTime)
    },

    // 视频时间更新中
    onPlayerTimeupdate(player) {
      // console.log('Timeupdate>视频时间更新中!', player);
      const currentTime = player.cache_.currentTime // 当前播放时长
      const duration = player.cache_.duration // 视频总时长

      // 该事件 1s 内会激发多次，只有每 1s 内第一次会向后台发送请求，其他几次均不会向后台发送
      if (this.studyPoint && this.studyPoint === parseInt(currentTime)) {
        console.log('不向后台发送请求', duration, currentTime)
        return
      }

      // 每 10s 记录一次进度
      this.studyPoint = parseInt(currentTime)
      if (this.studyPoint % 10 === 0 && currentTime >= 10) {
        this.studyRecord(duration, currentTime)
      }
    },

    // 视频加载中
    onPlayerWaiting(player) {
      console.log('Waiting>视频加载中!', player)
    },

    // 视频状态改变
    playerStateChanged(playerCurrentState) {
      console.log('StateChanged>视频状态改变', playerCurrentState)
    },
    // --------------------视频播放-结束-------------------- */

    videoPlayByPeriodId(periodId) {
      // 层层上调的目的是为了同步页面上所有（两个）章节列表的状态（）
      this.$emit('playfunc', periodId)
    },

    action(data, autoplay) {
      if (!this.tokenInfo) {
        this.$msgBox({
          content: '请先登录'
        }).then(res => {
          this.$store.dispatch('REDIRECT_LOGIN')
        }).catch(() => {
        })
        return false
      }

      const mainResourceUrl = data.playPeriod.mainResourceUrl
      if (mainResourceUrl === null || mainResourceUrl.length === 0) {
        this.$msgBox({
          content: '该视频未更新',
          isShowCancelBtn: false
        }).catch(() => {
        })
        return false
      }

      // 设置播放器背景
      // this.$refs.watchVideo.playerOptions.poster = this.courseInfo.courseLogo
      this.playerOptions = {}
      playerOptions.sources[0] = {
        type: 'video/mp4', // 资源格式写法：'video/mp4'
        src: mainResourceUrl // 本地资源地址，注意：本地资源存放在public文件夹中，本文视频资源路径public/video/1.mp4
      }
      playerOptions.autoplay = autoplay

      this.playerOptions = playerOptions

      this.userStudy.studyId = data.studyId
      this.userStudy.periodId = data.playPeriod.id
    },
    // 记录进度
    studyRecord(duration, currentTime) {
      this.userStudy.totalDuration = duration
      this.userStudy.currentDuration = currentTime
      console.log('开始同步 userStudy is:', this.userStudy)
      studyProgress(this.userStudy).then(res => {
        if (res === 'OK') {
          // 完成，暂停同步
          console.log('同步完成 userStudy is:', this.userStudy)
        }
      })
    }
  }
}
</script>
<style lang="scss" rel="stylesheet/scss">
.detail_video {
  background: #fff;
}

.video_header {
  height: 66px;
  width: 1200px;
  margin: 0 auto;

  li {
    float: left;
    line-height: 66px;
  }

  .header_left {
    float: left;

    a {
      color: #999;
      margin-left: 10px;

      &:hover {
        text-decoration: none;
        color: #333;
      }
    }

    .left_30 {
      margin-left: 30px;
    }

    .return_btn {
      width: 66px;
      height: 66px;

      &:hover {
        background: #f6f8fb;
      }
    }

    .return_img {
      width: 20px;
      height: 20px;
      margin-left: 23px;
      margin-top: 23px;
    }

    .vider_title {
      font-size: 16px;
      font-weight: 700;
      color: #333;
      margin-left: 20px;

      a:hover {
        color: #d51423;
      }

      .c_red {
        color: #d51423;
      }
    }
  }

  .header_right {
    float: right;

    a {
      padding: 0 10px;
      font-size: 12px;
      color: #333;

      &:hover {
        text-decoration: none;
        color: #D51423;
      }

      &.c_gold {
        color: #CA9E70;
      }

      &.no_left {
        padding-left: 0px;
      }
    }

    .left_col {
      border-left: 1px solid #ccc;
    }

    .pd_0 {
      padding-left: 0px;
    }

    .vip_icon {
      width: 14px;
      height: 13px;
      position: relative;
      left: -10px;
      top: 1px;
      cursor: pointer;
    }
  }
}

.video_body {
  background: rgb(51, 51, 51);

  .video_content {
    width: 1200px;
    margin: 0 auto;
    position: relative;
    overflow: hidden;
  }

  .win_box {
    float: left;
    width: 1120px;
    // height: 595px;
    margin: 5px 0;
    border-radius: 8px;
    //  border: 5px solid #000;
  }

  .video_win {
    width: 1110px;
    height: 585px;
    -webkit-background-size: 100%;
    background-size: 100%;

    &.mini_win {
      width: 600px;
      height: 295px;
      position: fixed;
      right: 10px;
      bottom: 30px;
      z-index: 9999;
    }
  }

  .video-js {
    height: 595px;
  }

  .video_info {
    position: relative;
    z-index: 41;
    float: right;
    padding-top: 20px;
    height: 595px;
    background-color: #333;

    a {
      overflow: hidden;
      display: block;
      height: 86px;
      width: 69px;
      color: #ccc;

      &:hover, &.on {
        text-decoration: none;
        background: #000;
      }
    }

    i {
      display: block;
      width: 24px;
      height: 23px;
      margin: 20px 20px 10px 20px;
      font-size: 26px;
    }

    p {
      font-size: 14px;
      text-align: center;
      color: #ccc;
    }
  }
}

.cate_panel {
  position: absolute;
  z-index: 11;
  top: 0;
  right: -350px;
  background-color: #000;
  height: 595px;
  width: 400px;
  padding: 20px;
  overflow: auto;
  transition: all .5s;
  z-index: 40;

  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background: rgba(255, 255, 255, 0.4);
  }

  dl {
    margin-bottom: 10px;
  }

  dt {
    color: #fff;
    font-size: 14px;
    line-height: 18px;
  }

  dd {
    color: #999;
    line-height: 26px;
    padding-left: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    i {
      font-size: 14px;
      margin-right: 8px;
    }

    a {
      color: #999;
    }

    &:hover, &.on, a:hover {
      color: #D51423;
      cursor: pointer;
      text-decoration: none;
    }
  }

  .load_more {
    text-align: center;
    color: #ccc;
  }
}

.show_panel {
  .cate_panel {
    right: 69px;
  }
}

.no_video {
  color: #999;
}

.no_video2 {
  color: #eee;
}

.info_box {
  pre {
    white-space: inherit;
  }
}
</style>
